<template>
  <div class="text-generation-page">
    <!-- 顶部导航 -->
    <van-nav-bar
      title="文本生成"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      class="custom-nav-bar"
    >
      <template #right>
        <van-icon name="delete-o" @click="clearHistory" />
      </template>
    </van-nav-bar>

    <!-- 功能介绍 -->
    <div class="feature-intro">
      <div class="intro-content">
        <div class="intro-icon">✍️</div>
        <div class="intro-text">
          <h3>AI文本生成{{ currentMode ? ` - ${currentMode}` : '' }}</h3>
          <p>创意写作助手，帮你写作文、故事、诗歌等各种文本内容</p>
        </div>
      </div>

      <!-- 写作类型标签 -->
      <div class="writing-tabs">
        <div class="mode-title">选择写作类型：</div>
        <div class="tabs-container">
          <div
            v-for="mode in writingModes"
            :key="mode.name"
            :class="['mode-tab', { active: currentMode === mode.name }]"
            @click="selectMode(mode)"
          >
            <span class="tab-icon">{{ mode.icon }}</span>
            <span class="tab-name">{{ mode.name }}</span>
          </div>
        </div>
      </div>

      <!-- 示例创作 -->
      <div class="intro-examples" v-if="currentMode">
        <div class="example-title">💡 试试这些{{ currentMode }}创作：</div>
        <div class="example-tags">
          <span
            v-for="example in currentExamples"
            :key="example"
            class="example-tag"
            @click="askExample(example)"
          >
            {{ example }}
          </span>
        </div>
      </div>
    </div>

    <!-- 对话区域 -->
    <div class="chat-container" ref="chatContainer">
      <div v-if="messages.length === 0" class="empty-chat">
        <div class="empty-icon">📝</div>
        <p>请告诉我你想创作什么内容</p>
      </div>

      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message-item', message.type]"
      >
        <div class="message-avatar">
          {{ message.type === 'user' ? '👤' : '✍️' }}
        </div>
        <div class="message-content">
          <div class="message-text" v-html="formatMessage(message.content)"></div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          <div v-if="message.type === 'ai'" class="message-actions">
            <van-button size="mini" type="default" @click="copyText(message.content)">
              复制
            </van-button>
            <van-button size="mini" type="primary" @click="continueWriting(message.content)">
              继续创作
            </van-button>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="message-item ai loading">
        <div class="message-avatar">✍️</div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <div class="input-wrapper">
        <van-field
          v-model="inputText"
          placeholder="请描述你想创作的内容..."
          type="textarea"
          rows="2"
          autosize
          @keyup.enter="sendMessage"
          class="message-input"
        />
        <van-button
          type="primary"
          size="large"
          :loading="isLoading"
          @click="sendMessage"
          class="send-btn"
          :disabled="!inputText.trim()"
        >
          <van-icon name="edit" />
        </van-button>
      </div>

      <!-- 智能功能 -->
      <div class="smart-features">
        <div class="feature-item" @click="showWritingTemplates">
          <van-icon name="notes-o" />
          <span>写作模板</span>
        </div>
        <div class="feature-item" @click="showCreationHistory">
          <van-icon name="clock-o" />
          <span>创作历史</span>
        </div>
        <div class="feature-item" @click="toggleDarkMode">
          <van-icon :name="isDarkMode ? 'sun-o' : 'moon-o'" />
          <span>{{ isDarkMode ? '浅色' : '深色' }}</span>
        </div>
        <div class="feature-item" @click="exportCreations">
          <van-icon name="down" />
          <span>导出作品</span>
        </div>
      </div>
    </div>

    <!-- 写作模板弹窗 -->
    <van-popup v-model:show="showTemplatePopup" position="bottom" :style="{ height: '70%' }">
      <div class="template-popup">
        <div class="popup-header">
          <h3>写作模板</h3>
          <van-button size="small" @click="showTemplatePopup = false">关闭</van-button>
        </div>
        <div class="popup-content">
          <div class="category-tabs">
            <div
              v-for="category in templateCategories"
              :key="category.name"
              :class="['category-tab', { active: activeTemplateCategory === category.name }]"
              @click="activeTemplateCategory = category.name"
            >
              {{ category.icon }} {{ category.name }}
            </div>
          </div>
          <div class="templates-list">
            <div
              v-for="template in currentTemplates"
              :key="template.title"
              class="template-item"
              @click="selectTemplate(template)"
            >
              <div class="template-title">{{ template.title }}</div>
              <div class="template-desc">{{ template.description }}</div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 创作历史弹窗 -->
    <van-popup v-model:show="showHistoryPopup" position="bottom" :style="{ height: '60%' }">
      <div class="history-popup">
        <div class="popup-header">
          <h3>创作历史</h3>
          <div class="header-actions">
            <van-button size="small" @click="clearCreationHistory">清空</van-button>
            <van-button size="small" @click="showHistoryPopup = false">关闭</van-button>
          </div>
        </div>
        <div class="popup-content">
          <div v-if="creationHistory.length === 0" class="empty-history">
            <div class="empty-icon">📝</div>
            <p>暂无创作历史</p>
          </div>
          <div v-else class="history-list">
            <div
              v-for="(item, index) in creationHistory"
              :key="index"
              class="history-item"
              @click="selectHistoryItem(item)"
            >
              <div class="history-content">
                <div class="history-title">{{ item.title || '无标题创作' }}</div>
                <div class="history-preview">{{ getContentPreview(item.content) }}...</div>
                <div class="history-time">{{ formatTime(item.timestamp) }}</div>
              </div>
              <van-icon name="arrow" />
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, computed } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { useRoute } from 'vue-router'
import aiService from '@/services/aiService'
import { saveUserData, loadUserData, getCurrentUserId, migrateOldData } from '@/utils/userDataManager'

const route = useRoute()

// 响应式数据
const inputText = ref('')
const messages = ref<Array<{
  type: 'user' | 'ai'
  content: string
  timestamp: number
}>>([])
const isLoading = ref(false)
const chatContainer = ref<HTMLElement>()
const currentMode = ref<string>('')

// 写作模式配置
const writingModes = ref([
  {
    name: '创意写作',
    icon: '🎨',
    description: '激发创意灵感写作',
    examples: ['写一首关于春天的诗', '创作一个科幻故事', '写一段优美的散文', '编一个童话故事']
  },
  {
    name: '商务文案',
    icon: '💼',
    description: '专业商务文案撰写',
    examples: ['写一份产品介绍', '撰写营销文案', '写一份商业计划书摘要', '创作广告语']
  },
  {
    name: '学术论文',
    icon: '🎓',
    description: '学术论文写作指导',
    examples: ['写一篇论文摘要', '撰写文献综述', '写研究方法介绍', '创作学术报告']
  },
  {
    name: '诗歌创作',
    icon: '🌸',
    description: '诗歌创作与鉴赏',
    examples: ['写一首现代诗', '创作古体诗', '写一首抒情诗', '创作打油诗']
  },
  {
    name: '故事续写',
    icon: '📖',
    description: '故事情节续写创作',
    examples: ['续写一个悬疑故事', '完成童话结局', '续写科幻小说', '创作故事开头']
  }
])

// 当前示例创作
const currentExamples = computed(() => {
  if (!currentMode.value) return []
  const mode = writingModes.value.find(m => m.name === currentMode.value)
  return mode ? mode.examples : []
})

// 发送消息
const sendMessage = async () => {
  const prompt = inputText.value.trim()
  if (!prompt || isLoading.value) return

  // 添加用户消息
  const userMsg = {
    type: 'user',
    content: prompt,
    timestamp: Date.now()
  }
  messages.value.push(userMsg)

  inputText.value = ''
  isLoading.value = true

  await scrollToBottom()

  // 添加AI消息占位符
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    timestamp: Date.now()
  })

  let accumulatedText = ''

  try {
    // 使用流式输出
    await aiService.textGenerationStream(
      12345,
      prompt,
      // onMessage回调
      (content: string) => {
        accumulatedText += content
        messages.value[aiMessageIndex].content = accumulatedText
        scrollToBottom()
      },
      // onComplete回调
      () => {
        // 保存到创作历史
        const title = extractTitle(prompt)
        const aiResponse = messages.value[aiMessageIndex].content

        // 确保内容是字符串格式
        let content = ''
        if (typeof aiResponse === 'string') {
          content = aiResponse
        } else if (typeof aiResponse === 'object' && aiResponse) {
          content = aiResponse.text || aiResponse.content || aiResponse.response || JSON.stringify(aiResponse)
        } else {
          content = String(aiResponse || '生成完成')
        }

        creationHistory.value.unshift({
          title: String(title || '无标题创作'),
          content: content,
          timestamp: Date.now()
        })

        if (creationHistory.value.length > 30) {
          creationHistory.value = creationHistory.value.slice(0, 30)
        }
        saveToLocal('history', creationHistory.value)

        isLoading.value = false
        scrollToBottom()
      },
      // onError回调
      async (error: any) => {
        console.error('流式输出失败，尝试非流式输出:', error)

        // 流式输出失败，尝试非流式输出
        try {
          const response = await aiService.textGeneration(12345, prompt, 'creative')
          if (response.code === 200) {
            messages.value[aiMessageIndex].content = response.data || '创作完成！'
          } else {
            messages.value[aiMessageIndex].content = '抱歉，我现在无法完成这个创作。请稍后再试。'
          }
        } catch (fallbackError) {
          console.error('非流式输出也失败:', fallbackError)
          messages.value[aiMessageIndex].content = '抱歉，我现在无法完成这个创作。请稍后再试。'
        }

        // 保存到创作历史
        const title = extractTitle(prompt)
        const aiResponse = messages.value[aiMessageIndex].content

        // 确保内容是字符串格式
        let content = ''
        if (typeof aiResponse === 'string') {
          content = aiResponse
        } else if (typeof aiResponse === 'object' && aiResponse) {
          content = aiResponse.text || aiResponse.content || aiResponse.response || JSON.stringify(aiResponse)
        } else {
          content = String(aiResponse || '生成完成')
        }

        creationHistory.value.unshift({
          title: String(title || '无标题创作'),
          content: content,
          timestamp: Date.now()
        })

        if (creationHistory.value.length > 30) {
          creationHistory.value = creationHistory.value.slice(0, 30)
        }
        saveToLocal('history', creationHistory.value)

        isLoading.value = false
        scrollToBottom()
      }
    )

  } catch (error) {
    console.error('文本生成失败:', error)

    // 备选方案：直接调用非流式API
    try {
      const response = await aiService.textGeneration(12345, prompt, 'creative')
      if (response.code === 200) {
        messages.value[aiMessageIndex].content = response.data || '创作完成！'
      } else {
        messages.value[aiMessageIndex].content = '抱歉，我现在无法完成这个创作。请稍后再试。'
      }
    } catch (fallbackError) {
      console.error('备选方案失败:', fallbackError)
      messages.value[aiMessageIndex].content = '抱歉，我现在无法完成这个创作。请稍后再试。'
    }

    // 保存到创作历史
    const title = extractTitle(prompt)
    const aiResponse = messages.value[aiMessageIndex].content

    // 确保内容是字符串格式
    let content = ''
    if (typeof aiResponse === 'string') {
      content = aiResponse
    } else if (typeof aiResponse === 'object' && aiResponse) {
      content = aiResponse.text || aiResponse.content || aiResponse.response || JSON.stringify(aiResponse)
    } else {
      content = String(aiResponse || '生成完成')
    }

    creationHistory.value.unshift({
      title: String(title || '无标题创作'),
      content: content,
      timestamp: Date.now()
    })

    if (creationHistory.value.length > 30) {
      creationHistory.value = creationHistory.value.slice(0, 30)
    }
    saveToLocal('history', creationHistory.value)

    isLoading.value = false
    await scrollToBottom()
  }
}

// 提取标题
const extractTitle = (prompt: string): string => {
  // 从提示词中提取可能的标题
  const titlePatterns = [
    /题目[是：](.+?)[\n。，]/,
    /主题[是：](.+?)[\n。，]/,
    /写(.+?)[\n。，]/,
    /关于(.+?)的/
  ]

  for (const pattern of titlePatterns) {
    const match = prompt.match(pattern)
    if (match) {
      return match[1].trim()
    }
  }

  // 如果没有找到明确的标题，使用前20个字符
  return prompt.slice(0, 20) + (prompt.length > 20 ? '...' : '')
}

// 已删除模拟数据生成函数，现在使用真实API

// 已删除所有模拟内容生成函数

// 继续删除模拟函数...

// 已删除所有模拟内容生成函数，现在使用真实API

// 点击示例创作
const askExample = (example: string) => {
  inputText.value = example
  sendMessage()
}

// 新增功能状态
const showTemplatePopup = ref(false)
const showHistoryPopup = ref(false)
const activeTemplateCategory = ref('作文')
const isDarkMode = ref(false)

// 本地存储功能
const creationHistory = ref<Array<{title: string, content: string, timestamp: number}>>([])

// 写作模板分类
const templateCategories = ref([
  {
    name: '作文',
    icon: '📝',
    templates: [
      {
        title: '议论文模板',
        description: '观点明确，论证有力的议论文结构',
        prompt: '请帮我写一篇议论文，题目是：[请输入题目]。要求：1.观点明确 2.论证充分 3.结构清晰 4.语言流畅'
      },
      {
        title: '记叙文模板',
        description: '生动有趣的记叙文写作',
        prompt: '请帮我写一篇记叙文，主题是：[请输入主题]。要求：1.情节生动 2.描写细腻 3.情感真挚 4.结构完整'
      },
      {
        title: '说明文模板',
        description: '条理清晰的说明文结构',
        prompt: '请帮我写一篇说明文，说明对象是：[请输入对象]。要求：1.条理清晰 2.语言准确 3.方法多样 4.通俗易懂'
      }
    ]
  },
  {
    name: '诗歌',
    icon: '🎭',
    templates: [
      {
        title: '现代诗模板',
        description: '富有意境的现代诗创作',
        prompt: '请帮我创作一首现代诗，主题是：[请输入主题]。要求：1.意境优美 2.语言精练 3.情感真挚 4.富有想象力'
      },
      {
        title: '古体诗模板',
        description: '传统格律的古体诗',
        prompt: '请帮我创作一首古体诗，主题是：[请输入主题]。要求：1.格律工整 2.意境深远 3.用词典雅 4.情景交融'
      },
      {
        title: '儿童诗模板',
        description: '天真活泼的儿童诗',
        prompt: '请帮我创作一首儿童诗，主题是：[请输入主题]。要求：1.语言简单 2.富有童趣 3.朗朗上口 4.想象丰富'
      }
    ]
  },
  {
    name: '故事',
    icon: '📚',
    templates: [
      {
        title: '短篇小说模板',
        description: '精彩的短篇小说创作',
        prompt: '请帮我创作一个短篇小说，主题是：[请输入主题]。要求：1.情节紧凑 2.人物鲜明 3.语言生动 4.结局出人意料'
      },
      {
        title: '童话故事模板',
        description: '富有想象力的童话',
        prompt: '请帮我创作一个童话故事，主角是：[请输入主角]。要求：1.想象丰富 2.寓意深刻 3.语言优美 4.适合儿童'
      },
      {
        title: '科幻故事模板',
        description: '充满科技感的科幻故事',
        prompt: '请帮我创作一个科幻故事，背景是：[请输入背景]。要求：1.科技元素丰富 2.逻辑合理 3.想象大胆 4.引人深思'
      }
    ]
  },
  {
    name: '应用文',
    icon: '📄',
    templates: [
      {
        title: '演讲稿模板',
        description: '有感染力的演讲稿',
        prompt: '请帮我写一份演讲稿，主题是：[请输入主题]。要求：1.开头吸引人 2.逻辑清晰 3.语言有力 4.结尾升华'
      },
      {
        title: '书信模板',
        description: '真挚感人的书信',
        prompt: '请帮我写一封信，收信人是：[请输入收信人]，内容是：[请输入内容]。要求：1.格式正确 2.情感真挚 3.语言得体'
      },
      {
        title: '日记模板',
        description: '记录生活的日记',
        prompt: '请帮我写一篇日记，记录的事情是：[请输入事情]。要求：1.真实自然 2.情感丰富 3.语言朴实 4.有感悟'
      }
    ]
  }
])

// 当前模板
const currentTemplates = computed(() => {
  const category = templateCategories.value.find(c => c.name === activeTemplateCategory.value)
  return category ? category.templates : []
})

// 从本地存储加载数据
const loadLocalData = () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) {
      console.warn('⚠️ 用户未登录，无法加载个人数据')
      return
    }

    // 迁移旧数据（如果存在）
    migrateOldData('textGeneration', [
      { oldKey: 'textGeneration_history', dataType: 'history' },
      { oldKey: 'textGeneration_darkMode', dataType: 'darkMode' }
    ])

    // 加载用户专属数据
    const rawHistory = loadUserData('textGeneration', 'history', [])
    // 清理和验证历史数据
    creationHistory.value = cleanHistoryData(rawHistory)
    isDarkMode.value = loadUserData('textGeneration', 'darkMode', false)

    // 应用深色模式
    document.documentElement.classList.toggle('dark-mode', isDarkMode.value)

    console.log(`✅ 文本生成数据已加载 - 用户ID: ${userId}`)
  } catch (error) {
    console.error('❌ 加载本地数据失败:', error)
  }
}

// 保存到本地存储
const saveToLocal = (key: string, data: any) => {
  const success = saveUserData('textGeneration', key, data)
  if (!success) {
    console.warn('⚠️ 保存数据失败，用户可能未登录')
  }
}

// 显示写作模板
const showWritingTemplates = () => {
  showTemplatePopup.value = true
}

// 选择模板
const selectTemplate = (template: any) => {
  inputText.value = template.prompt
  showTemplatePopup.value = false
  nextTick(() => {
    // 可以选择是否自动发送
    // sendMessage()
  })
}

// 显示创作历史
const showCreationHistory = () => {
  showHistoryPopup.value = true
}

// 选择历史项目
const selectHistoryItem = (item: any) => {
  // 安全获取内容
  let content = ''
  if (typeof item.content === 'string') {
    content = item.content
  } else if (typeof item.content === 'object') {
    content = item.content.text || item.content.content || item.content.response || JSON.stringify(item.content)
  } else {
    content = String(item.content || '无内容')
  }

  inputText.value = `请继续创作或修改这个作品：\n\n${content}`
  showHistoryPopup.value = false
  nextTick(() => {
    // sendMessage()
  })
}

// 清空创作历史
const clearCreationHistory = () => {
  creationHistory.value = []
  saveToLocal('history', creationHistory.value)
  showToast('创作历史已清空')
}

// 切换深色模式
const toggleDarkMode = () => {
  isDarkMode.value = !isDarkMode.value
  document.documentElement.classList.toggle('dark-mode', isDarkMode.value)
  saveToLocal('darkMode', isDarkMode.value)
  showToast(isDarkMode.value ? '已切换到深色模式' : '已切换到浅色模式')
}

// 导出创作作品
const exportCreations = () => {
  if (messages.value.length === 0) {
    showToast('暂无创作内容可导出')
    return
  }

  const content = messages.value
    .filter(msg => msg.type === 'ai')
    .map((msg, index) => `作品 ${index + 1}:\n${msg.content}`)
    .join('\n\n' + '='.repeat(50) + '\n\n')

  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `AI创作作品集-${new Date().toLocaleDateString()}.txt`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)

  showToast('创作作品已导出到文件')
}

// 清理历史数据
const cleanHistoryData = (rawHistory: any[]): Array<{title: string, content: string, timestamp: number}> => {
  if (!Array.isArray(rawHistory)) return []

  return rawHistory.filter(item => {
    // 确保每个项目都有必要的字段
    return item && typeof item === 'object' && item.timestamp
  }).map(item => {
    // 标准化数据格式
    let content = ''
    if (typeof item.content === 'string') {
      content = item.content
    } else if (typeof item.content === 'object' && item.content) {
      content = item.content.text || item.content.content || item.content.response || JSON.stringify(item.content)
    } else {
      content = String(item.content || '无内容')
    }

    return {
      title: String(item.title || '无标题创作'),
      content: content,
      timestamp: Number(item.timestamp) || Date.now()
    }
  })
}

// 安全获取内容预览
const getContentPreview = (content: any): string => {
  if (!content) return '暂无内容'

  // 如果是字符串，直接截取
  if (typeof content === 'string') {
    return content.slice(0, 50)
  }

  // 如果是对象，尝试提取文本内容
  if (typeof content === 'object') {
    if (content.text) return String(content.text).slice(0, 50)
    if (content.content) return String(content.content).slice(0, 50)
    if (content.response) return String(content.response).slice(0, 50)
    // 如果是对象但没有明确的文本字段，转换为JSON字符串
    return JSON.stringify(content).slice(0, 50)
  }

  // 其他类型转换为字符串
  return String(content).slice(0, 50)
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const now = Date.now()
  const diff = now - timestamp

  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return new Date(timestamp).toLocaleDateString()
  }
}

// 复制文本
const copyText = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    showToast('已复制到剪贴板')
  } catch (error) {
    showToast('复制失败')
  }
}

// 继续创作
const continueWriting = (text: string) => {
  inputText.value = `请基于以下内容继续创作：\n\n${text}`
  sendMessage()
}

// 格式化消息内容
const formatMessage = (content: string) => {
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/\n/g, '<br>')
}



// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 清空历史
const clearHistory = async () => {
  try {
    await showConfirmDialog({
      title: '确认清空',
      message: '确定要清空所有创作记录吗？'
    })

    messages.value = []
    showToast('创作记录已清空')
  } catch {
    // 用户取消
  }
}

onMounted(() => {
  // 加载本地数据
  loadLocalData()

  // 添加欢迎消息
  messages.value.push({
    type: 'ai',
    content: '你好！我是AI文本生成助手 ✍️\n\n我可以帮你创作各种文本内容，包括作文、诗歌、故事、应用文等。\n\n✨ **新功能提示**：\n• 点击"写作模板"查看专业模板\n• 使用"创作历史"回顾之前的作品\n• 切换"深色模式"保护眼睛\n• "导出作品"保存精彩创作\n\n**支持创作类型**：议论文、记叙文、现代诗、古体诗、短篇故事、童话等\n\n请告诉我你想创作什么，或者选择一个写作模板开始吧！',
    timestamp: Date.now()
  })
})
</script>

<style scoped>
.text-generation-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.feature-intro {
  margin: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.intro-content {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 16px;
}

.intro-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(240, 147, 251, 0.1);
  border-radius: 16px;
}

.intro-text h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.intro-text p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
  line-height: 1.4;
}

.example-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.example-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.example-tag {
  background: rgba(240, 147, 251, 0.1);
  color: #f093fb;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.example-tag:hover {
  background: rgba(240, 147, 251, 0.2);
  transform: translateY(-2px);
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.empty-chat {
  text-align: center;
  padding: 40px 20px;
  color: rgba(255, 255, 255, 0.8);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  max-width: 85%;
}

.message-item.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-item.ai {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  background: rgba(255, 255, 255, 0.9);
  flex-shrink: 0;
}

.message-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 12px 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.message-item.user .message-content {
  background: rgba(240, 147, 251, 0.9);
  color: white;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 8px;
}

.message-time {
  font-size: 12px;
  color: #95a5a6;
  text-align: right;
  margin-bottom: 8px;
}

.message-item.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.message-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #95a5a6;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.input-container {
  padding: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  margin-bottom: 12px;
}

.message-input {
  flex: 1;
  background: white;
  border-radius: 20px;
}

.send-btn {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

/* 智能功能区域样式 */
.smart-features {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 8px;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 12px 8px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  color: #64748b;
}

.feature-item:hover {
  background: #fef3f2;
  border-color: #f5576c;
  color: #f5576c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.2);
}

.feature-item .van-icon {
  font-size: 18px;
}

/* 弹窗样式 */
.template-popup,
.history-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
  background: linear-gradient(135deg, #fef3f2 0%, #fce7f3 100%);
}

.popup-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f8fafc;
}

.category-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
  overflow-x: auto;
  padding-bottom: 4px;
}

.category-tab {
  padding: 8px 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  font-size: 14px;
  color: #64748b;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.category-tab:hover {
  border-color: #f5576c;
  background: #fef3f2;
  transform: translateY(-1px);
}

.category-tab.active {
  background: linear-gradient(135deg, #f5576c 0%, #f093fb 100%);
  border-color: #f5576c;
  color: white;
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.3);
}

.templates-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.template-item {
  padding: 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.template-item:hover {
  background: #fef3f2;
  border-color: #f5576c;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.2);
}

.template-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.template-desc {
  font-size: 14px;
  color: #64748b;
  line-height: 1.4;
}

/* 历史记录样式 */
.empty-history {
  text-align: center;
  padding: 40px 20px;
  color: #64748b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background: #fef3f2;
  border-color: #f5576c;
  transform: translateX(4px);
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.2);
}

.history-content {
  flex: 1;
}

.history-title {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  margin-bottom: 4px;
}

.history-preview {
  font-size: 12px;
  color: #64748b;
  margin-bottom: 4px;
  line-height: 1.3;
}

.history-time {
  font-size: 12px;
  color: #94a3b8;
}

/* 增强输入区域样式 */
.input-container {
  background: linear-gradient(135deg, #ffffff 0%, #fef3f2 100%);
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
}

.message-input:focus-within {
  border-color: #f5576c;
  box-shadow: 0 0 0 3px rgba(245, 87, 108, 0.1);
}

.send-btn {
  background: linear-gradient(135deg, #f5576c 0%, #f093fb 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(245, 87, 108, 0.3);
  transition: all 0.3s ease;
}

.send-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(245, 87, 108, 0.4);
}

/* 深色模式支持 */
:global(.dark-mode) .text-generation-page {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
}

:global(.dark-mode) .custom-nav-bar {
  background: rgba(30, 41, 59, 0.95);
  color: white;
}

:global(.dark-mode) .feature-intro {
  background: #334155;
  border-color: #475569;
}

:global(.dark-mode) .intro-text h3 {
  color: #f1f5f9;
}

:global(.dark-mode) .intro-text p {
  color: #cbd5e1;
}

:global(.dark-mode) .message-item.ai .message-content {
  background: #334155;
  border-color: #475569;
}

:global(.dark-mode) .message-text {
  color: #f1f5f9;
}

:global(.dark-mode) .input-container {
  background: linear-gradient(135deg, #334155 0%, #475569 100%);
}

:global(.dark-mode) .message-input {
  background: #475569;
  border-color: #64748b;
  color: #f1f5f9;
}

:global(.dark-mode) .feature-item {
  background: #475569;
  border-color: #64748b;
  color: #cbd5e1;
}

:global(.dark-mode) .feature-item:hover {
  background: #be185d;
  border-color: #f5576c;
  color: white;
}

:global(.dark-mode) .template-popup,
:global(.dark-mode) .history-popup {
  background: #334155;
}

:global(.dark-mode) .popup-header {
  background: linear-gradient(135deg, #475569 0%, #64748b 100%);
}

:global(.dark-mode) .popup-header h3 {
  color: #f1f5f9;
}

:global(.dark-mode) .popup-content {
  background: #1e293b;
}

:global(.dark-mode) .category-tab {
  background: #475569;
  border-color: #64748b;
  color: #cbd5e1;
}

:global(.dark-mode) .template-item,
:global(.dark-mode) .history-item {
  background: #475569;
  border-color: #64748b;
  color: #cbd5e1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .smart-features {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .feature-item {
    padding: 16px 12px;
  }

  .category-tabs {
    gap: 6px;
  }

  .category-tab {
    padding: 6px 12px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .intro-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .smart-features {
    grid-template-columns: repeat(2, 1fr);
  }

  .feature-item {
    font-size: 11px;
    padding: 10px 6px;
  }

  .header-actions {
    flex-direction: column;
    gap: 4px;
  }

  .template-title {
    font-size: 14px;
  }

  .template-desc {
    font-size: 13px;
  }
}
</style>
